﻿@page
@model Shorter.Pages.Add

@{
    // Layout = null;
}

<!DOCTYPE html>

<html lang="ru">
<head>
    <title>Добавление ссылки</title>
</head>
<body>
<h4>Добавление ссылки</h4>
<div>
    <form action="javascript:handleAdd()">
        <label class="form-label">Описание</label>
        <input id="description" class="form-control" type="text"/>
        <label class="form-label">Ссылка</label>
        <input id="full" class="form-control" type="text"/>
        <br/>
        <input class="btn btn-primary" type="submit" value="Сократить"/>
    </form>
    <br/>

    <div id="result" style="display: none;">
        <span id="short"></span>
        <button onclick="copyToClipboard()">Копи</button>
    </div>
</div>

<script type="text/javascript">
function handleAdd() {
    const descriptionItem = $("#description")
    const fullItem = $("#full")
    const description = descriptionItem.val()
    const fullLink = fullItem.val()

    $("#result").hide()
    $("#short").text ("")

    if (!description || !fullLink) {
        return true
    }

    descriptionItem.val("")
    fullItem.val("")

    const data = {
        description: description,
        full: fullLink
    }

    $.ajax({
        url: "api/add",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify (data),
        type: "POST",
        success: function (result) {
            $("#result").show()
            $("#short").text (result)
        },
        error: function (xhr, status, error) {
            $("#result").show()
            $("#short").text (error)
        }
    })

    return true
}

function copyToClipboard() {
    const shortLink = $("#short").text()
    if (shortLink) {
        navigator.clipboard.writeText (shortLink)
    }
    
    return true;
}
</script>

</body>
</html>
